import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import '../../../data/services/api_service.dart';
import '../../../data/services/file_service.dart';
import '../../mine/controllers/mine_controller.dart';

class SettingController extends GetxController {
  // 服务实例 - GetX规范
  final ApiService _apiService = Get.find<ApiService>();
  final FileService _fileService = Get.find<FileService>();

  // 响应式变量
  final _isLoading = false.obs;
  final _userName = RxnString();
  final _avatarUrl = RxnString();
  final _isUploadingAvatar = false.obs;

  // Getters
  bool get isLoading => _isLoading.value;
  String? get userName => _userName.value;
  String? get avatarUrl => _avatarUrl.value;
  bool get isUploadingAvatar => _isUploadingAvatar.value;

  @override
  void onReady() {
    super.onReady();
    // 页面准备好后获取用户信息
    _loadUserInfo();
  }

  @override
  void onInit() {
    super.onInit();
    print('SettingController 初始化');
  }

  /// 刷新用户信息（公共方法）
  Future<void> refreshUserInfo() async {
    await _loadUserInfo();
  }

  /// 获取用户信息
  Future<void> _loadUserInfo() async {
    try {
      print('设置页面开始获取用户信息...');
      final response = await _apiService.getUserInfo();
      final data = response['data'] as Map<String, dynamic>?;

      if (data != null) {
        final newUserName = data['userName'] as String?;
        final newAvatarUrl = data['picUrl'] as String?;

        _userName.value = newUserName;
        _avatarUrl.value = newAvatarUrl;

        print('设置页面获取用户信息成功:');
        print('  用户名: $newUserName');
        print('  头像URL: $newAvatarUrl');

        // 强制更新界面
        update();
      }
    } catch (e) {
      print('设置页面获取用户信息失败: $e');
    }
  }

  /// 显示设置用户名弹框
  void showSetUsernameDialog() {
    final TextEditingController textController = TextEditingController();
    textController.text = _userName.value ?? '';

    Get.dialog(
      AlertDialog(
        title: Text(
          '设置昵称',
          style: TextStyle(
            fontSize: 32.sp,
            fontWeight: FontWeight.w600,
            color: const Color(0xFF333333),
          ),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: textController,
              decoration: InputDecoration(
                hintText: '请输入昵称',
                hintStyle: TextStyle(
                  fontSize: 28.sp,
                  color: const Color(0xFF999999),
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12.r),
                  borderSide: const BorderSide(color: Color(0xFFE1E1E1)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12.r),
                  borderSide: const BorderSide(color: Color(0xFF047FF7)),
                ),
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 20.w,
                  vertical: 16.h,
                ),
              ),
              style: TextStyle(fontSize: 28.sp, color: const Color(0xFF333333)),
              maxLength: 20,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text(
              '取消',
              style: TextStyle(fontSize: 28.sp, color: const Color(0xFF666666)),
            ),
          ),
          Obx(
            () => TextButton(
              onPressed:
                  _isLoading.value
                      ? null
                      : () => _updateUsername(textController.text.trim()),
              child:
                  _isLoading.value
                      ? SizedBox(
                        width: 20.w,
                        height: 20.h,
                        child: const CircularProgressIndicator(
                          strokeWidth: 2,
                          color: Color(0xFF047FF7),
                        ),
                      )
                      : Text(
                        '确定',
                        style: TextStyle(
                          fontSize: 28.sp,
                          color: const Color(0xFF047FF7),
                        ),
                      ),
            ),
          ),
        ],
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
      ),
    );
  }

  /// 更新用户名
  Future<void> _updateUsername(String newUsername) async {
    if (newUsername.isEmpty) {
      BotToast.showText(text: '昵称不能为空');
      return;
    }

    if (newUsername == _userName.value) {
      Get.back();
      return;
    }

    try {
      _isLoading.value = true;

      await _apiService.editUserInfo(username: newUsername);

      // 更新本地用户信息
      _userName.value = newUsername;

      BotToast.showText(text: '昵称设置成功');
      Get.back();

      // 通知个人中心页面重新获取用户信息
      notifyMinePageRefresh();

      print('用户名更新成功: $newUsername');
    } catch (e) {
      print('更新用户名失败: $e');
      BotToast.showText(text: '网络环境不佳，请稍后尝试');
    } finally {
      _isLoading.value = false;
    }
  }

  /// 选择并上传头像
  Future<void> selectAndUploadAvatar() async {
    try {
      // 显示选择选项
      await Get.bottomSheet(
        Container(
          height: 280.h,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.r),
              topRight: Radius.circular(20.r),
            ),
          ),
          child: Column(
            children: [
              SizedBox(height: 20.h),
              Text(
                '选择头像',
                style: TextStyle(
                  fontSize: 32.sp,
                  fontWeight: FontWeight.w600,
                  color: const Color(0xFF333333),
                ),
              ),
              SizedBox(height: 40.h),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  GestureDetector(
                    onTap: () async {
                      Get.back();
                      await _pickImageFromCamera();
                    },
                    child: Column(
                      children: [
                        Icon(
                          Icons.camera_alt,
                          size: 60.sp,
                          color: const Color(0xFF047FF7),
                        ),
                        SizedBox(height: 10.h),
                        Text(
                          '拍照',
                          style: TextStyle(
                            fontSize: 28.sp,
                            color: const Color(0xFF333333),
                          ),
                        ),
                      ],
                    ),
                  ),
                  GestureDetector(
                    onTap: () async {
                      Get.back();
                      await _pickImageFromGallery();
                    },
                    child: Column(
                      children: [
                        Icon(
                          Icons.photo_library,
                          size: 60.sp,
                          color: const Color(0xFF047FF7),
                        ),
                        SizedBox(height: 10.h),
                        Text(
                          '相册',
                          style: TextStyle(
                            fontSize: 28.sp,
                            color: const Color(0xFF333333),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 40.h),
            ],
          ),
        ),
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
      );
    } catch (e) {
      print('选择头像失败: $e');
      BotToast.showText(text: '网络环境不佳，请稍后尝试');
    }
  }

  /// 从相机拍照
  Future<void> _pickImageFromCamera() async {
    try {
      final AssetEntity? entity = await CameraPicker.pickFromCamera(
        Get.context!,
        pickerConfig: const CameraPickerConfig(
          enableRecording: false, // 只允许拍照，不允许录视频
          enableAudio: false,
          resolutionPreset: ResolutionPreset.high,
        ),
      );

      if (entity != null) {
        final File? file = await entity.file;
        if (file != null) {
          await _uploadAvatar(file);
        }
      }
    } catch (e) {
      print('拍照失败: $e');
      BotToast.showText(text: '网络环境不佳，请稍后尝试');
    }
  }

  /// 从相册选择图片
  Future<void> _pickImageFromGallery() async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        Get.context!,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1, // 只允许选择一张图片
          requestType: RequestType.image, // 只允许选择图片
          selectedAssets: [], // 初始选中的资源
          themeColor: const Color(0xFF047FF7), // 主题色
          textDelegate: const AssetPickerTextDelegate(), // 使用默认中文文本
          specialPickerType: SpecialPickerType.noPreview, // 不显示预览
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final AssetEntity asset = assets.first;
        final File? file = await asset.file;
        if (file != null) {
          await _uploadAvatar(file);
        }
      }
    } catch (e) {
      print('从相册选择图片失败: $e');
      BotToast.showText(text: '网络环境不佳，请稍后尝试');
    }
  }

  /// 上传头像
  Future<void> _uploadAvatar(File imageFile) async {
    try {
      _isUploadingAvatar.value = true;

      print('开始上传头像，文件路径: ${imageFile.path}');

      // 使用优化的头像上传方法（包含图片压缩）
      final uploadResponse = await _fileService.uploadAvatarImage(imageFile);
      final filePath = uploadResponse['data'] as String;
      print('文件上传成功，服务器路径: $filePath');

      // 获取文件访问地址
      final urlResponse = await _fileService.getFileUrl(filePath);
      final fileUrl = urlResponse['data'] as String;
      print('获取文件访问地址成功: $fileUrl');

      // 更新用户头像
      await _apiService.editUserInfo(picUrl: fileUrl);
      print('更新用户头像信息成功');

      // 立即更新本地头像显示
      _avatarUrl.value = fileUrl;
      print('本地头像已更新: $fileUrl');

      // 重新获取用户信息以确保数据一致性
      await refreshUserInfo();

      BotToast.showText(text: '头像上传成功');
      print('头像上传完成: $fileUrl');

      // 通知个人中心页面重新获取用户信息
      notifyMinePageRefresh();
    } catch (e) {
      print('上传头像失败: $e');

      // 根据错误类型显示不同的提示
      String errorMessage = '网络环境不佳，请稍后尝试';
      if (e.toString().contains('文件大小超过')) {
        errorMessage = '图片文件过大，请选择更小的图片';
      } else if (e.toString().contains('文件不存在')) {
        errorMessage = '图片文件不存在，请重新选择';
      }

      BotToast.showText(text: errorMessage);
    } finally {
      _isUploadingAvatar.value = false;
    }
  }

  /// 通知个人中心页面重新获取用户信息
  void notifyMinePageRefresh() {
    try {
      // 检查个人中心控制器是否存在，如果存在则刷新用户信息
      if (Get.isRegistered<MineController>()) {
        final mineController = Get.find<MineController>();
        // ✅ 强制刷新用户信息（包括头像）
        mineController.getUserInfo();
        print('✅ 已通知个人中心页面刷新用户信息');
      } else {
        print('⚠️ 个人中心控制器未注册，无法通知刷新');
      }
    } catch (e) {
      print('❌ 通知个人中心页面刷新失败: $e');
    }
  }
}
